package com.liuke.study.thread;

import javax.print.attribute.standard.Finishings;
import java.security.PrivateKey;
import java.sql.Connection;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * TODO
 *
 * @author wangjwy
 * @date 2019/10/18 14:21
 * @since 1.0.0
 */
public class Test4 {
	/*
		编写程序实现,子线程循环3次,接着主线程循环5次,接着再子线程循环3次,主线程循环5次,如此反复,循环3次.
	*/
	static volatile int count = 0;

	public static void main(String[] args) throws InterruptedException {
		// Lock lock = new ReentrantLock();
		// Condition conditionA = lock.newCondition();
		// Condition conditionB = lock.newCondition();
		//
		// MyThread myThread1 = new MyThread(5, conditionA, conditionB, lock);
		// MyThread myThread2 = new MyThread(3, conditionB, conditionA, lock);
		//
		// myThread1.start();
		// myThread2.start();


		Lock lock = new ReentrantLock();
		Condition condition1 = lock.newCondition();
		Condition condition2 = lock.newCondition();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try{
					lock.lock();
					Thread.sleep(200);
					System.out.println("获取了锁: " + Thread.currentThread().getName());
					condition1.signalAll();
					// System.out.println("23132131");
					// condition2.await();
				// } catch (InterruptedException e) {
				// 	e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
					System.out.println("释放了锁: " + Thread.currentThread().getName());
				}
			}
		}, "A线程").start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try{
					lock.lock();
					condition1.await();
					System.out.println("获取了锁: " + Thread.currentThread().getName());
					System.out.println("eeeeeeeee");
					condition2.signal();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
					System.out.println("释放了锁: " + Thread.currentThread().getName());
				}
			}
		}, "B线程").start();

		Thread.sleep(1000);
	}

	static class MyThread extends Thread {

		private int count;

		private Condition lockA;
		private Condition lockB;
		private Lock lock;

		public MyThread(Integer count, Condition lockA, Condition lockB, Lock lock) {
			this.count = count;
			this.lockA = lockA;
			this.lockB = lockB;
			this.lock = lock;
		}

		@Override
		public void run() {
			int iCount = 0;
			try {
				System.out.println("等待锁" + Thread.currentThread().getName());
				lock.tryLock();
				System.out.println("获取锁" + Thread.currentThread().getName());
				while (iCount < 3) {
					for (int i = 0; i < count; i++) {
						System.out.println(i + "线程名: " + Thread.currentThread().getName());
					}
					iCount++;
					lockA.await();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}

		}
	}
}
